package com.xwj.coupon.user.mq.producer;

import com.xwj.coupon.user.mq.message.CouponTemplateMessageBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Author: XuWenjie
 * @Date: 2025-08-13
 * @Description: MqProducer
 */
@Component
@Slf4j
public class CreateCouponTemplateMqProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private final String topic = "CouponTemplateTopic";
    private final String tag = "CREATE";
    public boolean sendCreateMessageOrderly(CouponTemplateMessageBody couponTemplate, String hashKey) {

        // 2. 构建顺序消息 (以订单ID作为hashKey)
        String destination = topic + ":" + tag; // "OrderTopic:CREATE"

        Message<CouponTemplateMessageBody> message = MessageBuilder.withPayload(couponTemplate)
                .setHeader(MessageConst.PROPERTY_KEYS, hashKey) // 设置KEYS方便查询
                .build();

        // 3. 同步顺序发送
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(destination, message, hashKey);
        log.info("sendMessage topic:{}-key[]-data[{}]-结果:{}", topic, message, sendResult.toString());
        return SendStatus.SEND_OK.equals(sendResult.getSendStatus());
         // 处理发送失败逻辑（重试、记录、告警等）
    }
}

